﻿using BaseData.CommonLib.Constants;
using BaseData.CommonLib.Models;
using Newtonsoft.Json;
using Swimj.CommonLib.Base;
using Swimj.Core.Extensions;
using System.Reflection;

namespace Production.RazorLib.Services
{
    public class MaterialService : IMaterialService
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public MaterialService(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<PaginatedResult<MaterialInfoResponseDto>?> QueryMaterialsByPage(MaterialSearchRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("basedataApi");
                var response = await httpClient.GetAsync(
                    model.ToQueryString(ApiRoutes.Material.QueryMaterials));
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<PaginatedResult<MaterialInfoResponseDto>>(resultJson);
                    }
                }

                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        public async Task<Result<IList<MaterialInfoResponseDto>>?> QueryMaterials(MaterialSearchRequestDto model)
        {
            try
            {
                var httpClient = _httpClientFactory.CreateClient("basedataApi");
                var response = await httpClient.GetAsync(
                    model.ToQueryString(ApiRoutes.Material.QueryMaterials));
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(resultJson))
                    {
                        return JsonConvert.DeserializeObject<Result<IList<MaterialInfoResponseDto>>>(resultJson);
                    }
                }

                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
    }
}